<template>
  <div ref="markdownViewer" />
</template>

<script>
import '@toast-ui/editor/dist/toastui-editor-viewer.css'
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer'

// 代码高亮
import 'highlight.js/styles/github.css'
import hljs from 'highlight.js'
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight'

// 图表
import 'tui-chart/dist/tui-chart.css'
import chart from '@toast-ui/editor-plugin-chart'

// 单元格合并
import tableMergedCell from '@toast-ui/editor-plugin-table-merged-cell'

// UML
import uml from '@toast-ui/editor-plugin-uml'

const chartOptions = {
  minWidth: 100,
  maxWidth: 600,
  minHeight: 100,
  maxHeight: 300
}

export default {
  name: 'MarkdownViewer',
  props: {
    height: {
      type: String,
      required: false,
      default: null
    },
    content: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      viewer: null
    }
  },
  watch: {
    content(newValue, preValue) {
      if (newValue !== preValue) {
        this.setValue(newValue)
      }
    }
  },
  mounted() {
    this.initViewer()
  },
  destroyed() {
    this.destroyViewer()
  },
  methods: {
    initViewer() {
      const options = {
        el: this.$refs.markdownViewer,
        initialValue: this.content,
        plugins: [[chart, chartOptions], [codeSyntaxHighlight, { hljs }], tableMergedCell, uml]
      }
      if (this.height) {
        options.height = this.height
      }
      this.viewer = new Viewer(options)
    },
    destroyViewer() {
      if (!this.viewer) return
      this.viewer.remove()
    },
    setValue(val) {
      this.viewer.setMarkdown(val)
    },
    getHtml() {
      return this.viewer.preview.getHTML()
    }
  }
}
</script>
